package com.csnj.admin.controller.SystemManager;

import com.csnj.admin.controller.form.ChangePwdForm;
import com.csnj.common.annotation.ApiNeedLog;
import com.csnj.common.annotation.ModelName;
import com.csnj.common.entity.APIResult;
import com.csnj.common.exception.IRCException;
import com.csnj.common.rest.BaseController;
import com.csnj.core.Srvs.SysManager.PermissionSrvs;
import com.csnj.core.Srvs.SysManager.SysMenuSrvs;
import com.csnj.core.Srvs.SysManager.SysUserSrvs;
import com.csnj.core.entity.SysUser;
import com.csnj.core.entity.VO.FrontUser;
import com.csnj.core.entity.VO.MenuTree;
import com.csnj.core.exception.DataNotExistException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * ${DESCRIPTION}
 *
 * @author wanghaobin
 * @create 2017-06-08 11:51
 */
@RestController
@RequestMapping("user")
@ModelName(ModelName = "用户")
public class UserController extends BaseController<SysUserSrvs, SysUser> {
    @Autowired
    PermissionSrvs permissionSrvs;
    @Autowired
    SysMenuSrvs sysMenuSrvs;

    @RequestMapping(value = "/menus", method = RequestMethod.GET)
    public APIResult getMenusByToken(String token) throws Exception {
        List<MenuTree> res = permissionSrvs.getMenusByToken(token);
        return new APIResult(res);
    }

    @RequestMapping(value = "/userinfo", method = RequestMethod.GET)
    public APIResult getUserInfo(String token) throws Exception {
        FrontUser userInfo = permissionSrvs.getUserInfo(token);
        request.getSession().setAttribute("uid", userInfo.getId().toString());
        request.getSession().setAttribute("name", userInfo.getName());
        return new APIResult(userInfo);
    }

    @RequestMapping(value = "/menu/all", method = RequestMethod.GET)
    public
    APIResult getAllMenus() throws Exception {
        return new APIResult(sysMenuSrvs.selectListAll());
    }

    @PostMapping(value = "/front/pwd")
    @ApiNeedLog(desc = "修改密码")
    public APIResult changeUserPassword(@RequestBody ChangePwdForm pwdForm) {
        try {
            return new APIResult(baseBiz.ChangePwd(pwdForm.getUserId(), pwdForm.getOldpwd(), pwdForm.getNewpwd()));
        } catch (IRCException e) {
            return new APIResult(e);
        }
    }

    @RequestMapping(value="resetPwd/{uid}")
    @ApiNeedLog(desc="重置密码")
    public APIResult resetUserPwd(@PathVariable Integer uid) {
        try {
            return new APIResult(baseBiz.ResetPwd(uid));
        } catch (DataNotExistException e) {
            return new APIResult(e);
        }
    }
}
